﻿using TianYuan.Core.Application.Services;
using TianYuan.Core.Dependency;
using Castle.Core;
using Castle.MicroKernel;
using System.Reflection;
using TianYuan.Core.Caching.Interception;
using System.Linq;
using TianYuan.Core.Caching;

namespace TianYuan.Data.Dapper
{
    public class SqlFilterInterceptorRegistrar
    {
        public static void Initialize(IIocManager iocManager)
        {
            iocManager.IocContainer.Kernel.ComponentRegistered += Kernel_ComponentRegistered;
        }

        private static void Kernel_ComponentRegistered(string key, IHandler handler)
        {
            if (handler.ComponentModel.Implementation.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                 .Any(m => m.IsDefined(typeof(TransactionalAttribute), true)))
            {
                handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(UnitOfWorkInterceptor)));
            }
        }
    }
}